<template>
<el-form :model="location" label-width="auto" style=" max-width: 100vw">
	
	<el-form-item>
		<el-row :gutter="20" class="el-row-align-center" style="width: 100%; background-color: lightblue;">
			
			<el-col :span="5" style="display: flex; align-items: center;">
				<span><h4>省区域：</h4></span>
				<el-select
				  v-model="location.provinceValue"
				  placeholder="--全部--"
				  style="width: 100px"
				  @change="handleProvinceChange"
				  size="default"
				>
				  <el-option				
					v-for="item in provinces"
					:key="item.id"
					:label="item.province"
					:value="item.id"
				  />
				</el-select>
	      </el-col>
	
	      <el-col :span="5" style="display: flex; align-items: center;">
				<span><h4>市区域：</h4></span>
				<el-select
				  v-model="location.cityValue"
				  placeholder="--全部--"
				  style="width: 150px"
				  :disabled="!location.provinceValue"
				  size="default"
				>
				  <el-option
					v-for="item in citys"
					:key="item.id"
					:label="item.areaName"
					:value="item.id"
				  />
				</el-select>
	      </el-col>
		  
			<el-col :span="5" style="display: flex; align-items: center;">
				<span><h4>确认日期：</h4></span>
				<el-date-picker
				  v-model="location.date"
				  type="date"
				  placeholder="确认日期"
				  style="width: 70%"
				/>
			</el-col>
			
			<el-col :span="5" style="display: flex; align-items: center;">
				<el-button type="danger" @click.prevent="handleClear">清空</el-button>
				<el-button type="primary" @click.prevent="handleCheck">查询</el-button>
			</el-col>
			
			<el-col :span="4" style="display: flex; align-items: center;">
				<el-radio-group v-model="location.designate" >
					<el-radio  value="0" >未指派</el-radio>
					<el-radio  value="1" >已指派</el-radio>
				</el-radio-group>
			</el-col>
		</el-row>
	  </el-form-item>
			
<el-form-item style="display: flex; align-items: center;">
      <el-table :data="pagedTableData" style="width: 100%">
              <el-table-column label="编号" width="120">
                <template #default="scope">
                  {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column prop="svName" label="反馈者姓名" width="180" />
              <el-table-column prop="province" label="所在省" />
              <el-table-column prop="city" label="所在市" />
              <el-table-column prop="feedback_aqi" label="预估污染等级" />
              <el-table-column prop="date" label="反馈日期" />
              <el-table-column prop="time" label="反馈时间" />
              <el-table-column fixed="right" label="操作" width="120">
                <template #default="scope">
					  <el-button
						link
						type="primary"
						size="large"
						@click.prevent="handleView(scope.$index)"
						circle
						:icon="View"
					  ></el-button>
					  <el-button
					  	v-if="location.designate == 0"
						link
						type="primary"
						size="large"
						@click.prevent="handleDesignate(scope.$index)"
						circle
						:icon="Pointer"
					  ></el-button>
				</template>
              </el-table-column>
            </el-table>

      <!-- Pagination -->
		<el-pagination
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
			:current-page="currentPage"
			:page-sizes="[5, 20, 30, 50]"
			:page-size="pageSize"
			layout="total, sizes, prev, pager, next, jumper"
			:total="tableData2.length"
		></el-pagination>
    </el-form-item>
</el-form>
</template>

<script  setup>
import { computed, ref, reactive, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router';
import axios from '@/axios';
import { useDateFormatter } from '@/composables/UserDateFormatter'
import {
  Document,
  Menu ,
  Location,
  Setting,
  Pointer,
  View,
  
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus';
const router=useRouter()
const route=useRoute()
const routequery=route.query
const tokenValue=localStorage.getItem('token')

const location=ref({
	provinceValue:'',
	cityValue:'',
	detailedAddress:'',
	designate:'0',
	date:'',
	aqi:'',	
	feedbackId:''
})

//监视是否指派
watch(()=>location.value.designate, async(newVal,oldVal)=>{
	if(location.value.designate){
		try{
			let state=location.value.designate
			axios.get('/service-admin/feedback/queryFeedback',
			{
				headers: {
				  'Authorization': `Bearer ${tokenValue}` // 在请求头中添加 Bearer Token
				},
				params:{
					cityId:location.value.cityValue==''?-1:location.value.cityValue,
					provinceId:location.value.provinceValue==''?-1:location.value.provinceValue,
					aqi:location.value.aqi==''?-1:location.value.aqi,
					date:location.value.date==''?-1:date.value,
					state:location.value.designate==''?-1:location.value.designate,
				},
			})
			.then(res=>{
				if(res.data.code==0)
				{
					tableData2.value=res.data.sendResult
					paginateData()
				}
				else{
					tableData2.value=''
					ElMessage.warning(res.data.sendResult)
				}
				
			})
		}catch(e){
			//TODO handle the exception
			console.error("报错")
		}
	}

})

const datalist=ref()
const tableData2=ref([])
const pagedTableData = ref([]); // 分页后的数据
const currentPage = ref(1); // 当前页码
const pageSize = ref(5); // 每页条数
const fetchData=async ()=>{
	try{
		axios.get('/service-admin/feedback/queryFeedback',
		{
			headers: {
			  'Authorization': `Bearer ${tokenValue}` // 在请求头中添加 Bearer Token
			},
			params:{
				cityId:location.value.cityValue==''?-1:location.value.cityValue,
				provinceId:location.value.provinceValue==''?-1:location.value.provinceValue,
				aqi:location.value.aqi==''?-1:location.value.aqi,
				date:location.value.date==''?-1:date.value,
				state:location.value.designate==''?-1:location.value.designate,
			},
		})
		.then(res=>{
			datalist.value=res.data.sendResult
			if(res.data.code==0)
			{
			tableData2.value=datalist.value
			paginateData(); // 分页处理数据
			console.log(tableData2.value)
			}
			else{
				tableData2.value=''
				paginateData(); // 分页处理数据
				ElMessage.warning(res.data.sendResult)
			}
		})
	}catch(err){
		console.error('Error fetching data:',err.message)
	}
}

// 分页处理数据
const paginateData = () => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  pagedTableData.value = tableData2.value.slice(startIndex, endIndex);
};

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  paginateData();
};
// 处理当前页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  paginateData();
};

const provinces = ref([])
const citys=ref([])
const fetchProvinces=async ()=>{
	try{
		axios.get('/service-admin/province/getAllProvince',
		{
			headers: {
			  'Authorization': `Bearer ${tokenValue}` // 在请求头中添加 Bearer Token
			},
		})
		  .then(response => {
			provinces.value=response.data.sendResult
			
		  })
		  .catch(error => {
			console.error('Error:', error);
		  });
	}catch(err){
		console.error('Error fetching data:',err.message)
	}

}

// 监听 location.value.provinceValue 的变化，计算出对应城市列表
watch(() => location.value.provinceValue, async (newVal, oldVal) => {
  if (location.value.provinceValue) {
	const provinceid = location.value.provinceValue;
	try {
	  const response = await axios.get('/service-admin/city/getByProvince', {
		params: {
		  provinceId: provinceid
		},
		headers: {
		  'Authorization': `Bearer ${tokenValue}` // 在请求头中添加 Bearer Token
		}
	  });
	  if(response.data.code==0)
	  {
		  citys.value = response.data.sendResult;
	  }
	  else{
		  citys.value=''
		  ElMessage.warning(response.data.sendResult)
	  }
	} catch (error) {
	  console.error('Error fetching cities:', error);
	}
  } else {
	console.error(`Province not found`);
  }
});

const handleProvinceChange = () => {
  location.value.cityValue = ''
}

//在组件挂载时调用fetchData函数和fetchProvinces函数
onMounted(()=>{
	fetchData()
	fetchProvinces()
})

const oneTableData=ref()
const handleView=(index)=>{
	oneTableData.value=tableData2.value[index]
	let data=oneTableData.value
	let gender=data.gender>1?'男':'女'
	console.log(oneTableData.value)
	router.push({
		path:'/admin/svDataManage/nextstep/detailed',
		query:{
			id:index+1,
			
			address:data.address,
			city:data.city,	
			province:data.province,	
			
			svName:data.svName,
			svGender:gender,
			svBirthday:data.svBirthday,
				
			svPhone:data.svPhone,
			
			content:data.content,
			
			aqi:data.aqiChinese,
			aqiChinese:data.aqiExplain,

			date:data.date,
			time:data.time
		}
	})
};
const handleDesignate=(index)=>{
	oneTableData.value=tableData2.value[index]
	let data=oneTableData.value
	let gender=data.gender>1?'男':'女'
	console.log(oneTableData.value)
	console.log(gender)
	router.push({
		path:'/admin/svDataManage/nextstep/designate',
		query:{
			id:index+1,
			feedbackId:datalist.value[index].id,
			address:data.address,
			city:data.city,	
			province:data.province,	
			svName:data.svName,
			svGender:gender,
			svBirthday:data.svBirthday,
			provinceId:data.province_id,
			svPhone:data.svPhone,
			cityId:data.city_id,
			content:data.content,
			aqi:data.aqiChinese,
			aqiChinese:data.aqiExplain,
			date:data.date,
			time:data.time
		}
	})
}

const handleClear = () => {
    location.value.provinceValue = ''
    location.value.cityValue = ''
    location.value.aqi = ''
    location.value.date = ''
};


const formattedDate=computed(()=>{
	return useDateFormatter( location.value.date,'yyyy-MM-dd hh:mm:ss').value
})
const date = computed(() => formattedDate.value.slice(0, 10))
const handleCheck= async ()=>{

	try{
		const response=await axios.get('/service-admin/feedback/queryFeedback',{
			params:{
				cityId:location.value.cityValue==''?-1:location.value.cityValue,
				provinceId:location.value.provinceValue==''?-1:location.value.provinceValue,
				aqi:location.value.aqi==''?-1:location.value.aqi,
				date:location.value.date==''?-1:location.value.date,
				state:location.value.designate==''?-1:location.value.designate
			},
			headers: {
			  'Authorization': `Bearer ${tokenValue}` // 在请求头中添加 Bearer Token
			},
		})
		if(response.data.code==0)
		{
			console.log("当前页是",currentPage.value)
			ElMessage.success("查询成功！")
			tableData2.value=response.data.sendResult
			console.log("当前页是",currentPage.value)
			paginateData(); // 分页处理数据
			console.log(pagedTableData.value)
			console.log(tableData2.value)
		}
		else{
			tableData2.value=[]
			paginateData(); // 分页处理数据
			console.log(pagedTableData.value)
			console.log(tableData2.value)
			ElMessage.warning(response.data.sendResult)
		}

	}catch(e){
		console.error(e.message)
	}
}
const AQI=[
	{
		label:'一级',
		value:'1',
	},
	{
		label:'二级',
		value:'2',
	},
	{
		label:'三级',
		value:'3',
	},
	{
		label:'四级',
		value:'4',
	},
	{
		label:'五级',
		value:'5',
	}
]



</script>

<style scoped>
	

</style>